const padLeft = function (content, totalWidth, paddingChar) {
  let len = content.toString().length;
  while (len < totalWidth) {
      content = paddingChar + content;
      len++;
  }
  return content;
}
const convertDate = function (obj) {
  // obj 为日期对象
  if (obj instanceof Date) {
    return obj;
  }
  // obj 为日期字符串
  if (typeof obj === 'string') {
    try {
      return new Date(obj)
    } catch (e) {
      if (typeof obj === 'number') {
        obj = obj.toString()
      }
    }
  }
  // obj 为时间戳的字符串, 1403058804
  obj = obj.replace("/Date(", "").replace(")/", "");
  let newDate = new Date();
  if (obj.length > 10 && obj.length <= 13) {
    obj = padLeft(obj, 13, '0');
    newDate.setTime(parseInt(obj));
  }
  if (obj.length <= 10) {
    obj = padLeft(obj, 10, '0');
    newDate.setTime(parseInt(obj) * 1000);
  }
  return newDate;
}
/**
 * 将日期转为日期格式
 * @type {convertDate}
 */
export const convertToDate = convertDate
// 格式化日期，用法：
// formatDate((new Date()),"yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// formatDate((new Date()),"yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
const innerFormatDate =  function (date, formatter) {
  if (date === null || date === "" || typeof date === 'undefined') {
    return ''
  }
  date = convertDate(date);
  if (formatter) {
    return date.format(formatter);
  }
  return date.format("yyyy-MM-dd hh:mm:ss");
}
/**
 * 时间格式化
 * @param date
 * @param fmt
 * @returns {*}
 */
export const formatDate = innerFormatDate
/**
 * 当前时间
 * @returns yyyy-mm-dd
 */
export const currentTime = function () {
  let date = new Date()
  let seperator1 = "-"
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = "0" + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate
  }
  let currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate
}
Date.prototype.format = function(fmt) {
  let o = {
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
/*
 * 重写时间的toJSON方法，因为在调用JSON.stringify的时候，时间转换就调用的toJSON，这样会导致少8个小时，所以重写它的toJSON方法
 */
Date.prototype.toJSON = function () {
  return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数
}
